// const webpack = require("webpack")
const path = require("path")
// const fs = require("fs")
const resolve = dir => path.join(__dirname, dir)
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV)
const IS_PRE_PROD = process.env.NODE_ENV == "prod"
console.log("IS_PROD:" + IS_PROD)
console.log("process.env.NODE_ENV:" + process.env.NODE_ENV)

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin
const CompressionWebpackPlugin = require("compression-webpack-plugin")

const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i

// console.log("process.env.IS_ANALYZE:" + process.env.IS_ANALYZE)
console.log("process.env.ABC:" + process.env.ABC)
module.exports = {
    // 默认'/'部署应用包时的基本 URL
    publicPath: IS_PROD ? process.env.VUE_APP_PUBLIC_PATH : "./",
    //当运行 vue-cli-service build 时生成的生产环境构建文件的目录
    outputDir: "dist",
    //放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录
    assetsDir: "assets",
    // eslint-loader 是否在保存的时候检查 安装@vue/cli-plugin-eslint有效
    lintOnSave: true,
    //是否使用包含运行时编译器的 Vue 构建版本。设置true后你就可以在使用template
    runtimeCompiler: true,
    // 生产环境是否生成 sourceMap 文件 sourceMap的详解请看末尾
    productionSourceMap: !IS_PROD,
    parallel: require("os").cpus().length > 1,
    pwa: {},

    //可以在正式环境下关闭错误报告 console.log...
    configureWebpack: config => {
        const plugins = []

        if (IS_PROD) {
            config.optimization = {
                splitChunks: {
                    cacheGroups: {
                        common: {
                            name: "chunk-common",
                            chunks: "initial",
                            minChunks: 2,
                            maxInitialRequests: 5,
                            minSize: 0,
                            priority: 1,
                            reuseExistingChunk: true,
                            enforce: true
                        },
                        vendors: {
                            name: "chunk-vendors",
                            test: /[\\/]node_modules[\\/]/,
                            chunks: "initial",
                            priority: 2,
                            reuseExistingChunk: true,
                            enforce: true
                        },
                        elementUI: {
                            name: "chunk-elementui",
                            test: /[\\/]node_modules[\\/]element-ui[\\/]/,
                            chunks: "all",
                            priority: 3,
                            reuseExistingChunk: true,
                            enforce: true
                        },
                        echarts: {
                            name: "chunk-echarts",
                            test: /[\\/]node_modules[\\/](vue-)?echarts[\\/]/,
                            chunks: "all",
                            priority: 4,
                            reuseExistingChunk: true,
                            enforce: true
                        }
                    }
                }
            }

            plugins.push(
                new CompressionWebpackPlugin({
                    filename: "[path].gz[query]",
                    algorithm: "gzip",
                    test: productionGzipExtensions,
                    threshold: 10240,
                    minRatio: 0.8
                })
            )
        }

        // config.externals = {
        //     vue: "Vue",
        //     "element-ui": "ELEMENT",
        //     "vue-router": "VueRouter",
        //     vuex: "Vuex",
        //     axios: "axios"
        // }
        config.plugins = [...config.plugins, ...plugins]
    },

    chainWebpack: config => {
        // 修复HMR
        config.resolve.symlinks(true)

        // 如果使用多页面打包，使用vue inspect --plugins查看html是否在结果数组中
        config.plugin("html").tap(args => {
            // 修复 Lazy loading routes Error
            args[0].chunksSortMode = "none"
            args[0].title = "vue-ci多分支自动化构建"
            return args
        })

        // 添加别名
        config.resolve.alias
            .set("vue$", "vue/dist/vue.esm.js")
            .set("@", resolve("src"))
            .set("@apis", resolve("src/apis"))
            .set("@assets", resolve("src/assets"))
            .set("@css", resolve("src/assets/css"))
            .set("@components", resolve("src/components"))
            .set("@middlewares", resolve("src/middlewares"))
            .set("@mixins", resolve("src/mixins"))
            .set("@plugins", resolve("src/plugins"))
            .set("@router", resolve("src/router"))
            .set("@store", resolve("src/store"))
            .set("@utils", resolve("src/utils"))
            .set("@views", resolve("src/views"))
            .set("@layouts", resolve("src/layouts"))

        if (IS_PROD) {
            config.optimization.delete("splitChunks")
        }
        if (IS_PRE_PROD) {
            config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
                {
                    analyzerMode: "static"
                }
            ])
        }

        return config
    },

    // css相关配置
    css: {
        // 是否使用css分离插件 ExtractTextPlugin 生产环境下是true,开发环境下是false
        extract: IS_PROD,
        // 开启 CSS source maps?
        sourceMap: false,
        // css预设器配置项
        loaderOptions: {
            // less:{
            // },
            // css:{
            // }
        },
        // 启用 CSS modules for all css / pre-processor files.
        requireModuleExtension: true
    },

    // webpack-dev-server 相关配置
    devServer: {
        // 设置代理`
        hot: true, //热加载
        host: "0.0.0.0", //ip地址
        port: 8086, //端口
        https: false, //false关闭https，true为开启
        open: true, //自动打开浏览器
        proxy: {
            "/api": {
                target: "http://192.168.102.13:8080/", //这里先随便写
                // 如果要代理 websockets
                ws: true, // 是否启用websockets
                changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
                pathRewrite: {
                    "^/api": "/"
                }
            }
        }
    },
    pluginOptions: {
        // 第三方插件配置
        // ...
    }
}
